package top.bug.blog.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import lombok.extern.slf4j.Slf4j;
import top.bug.blog.constant.PromptConstants;

import java.util.Arrays;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description Ai聊天工具类
 */
@Slf4j
public class ChatUtils {

    public static String getResult(String systemPrompt, String userPrompt, String apiKey, String model) {
        String content = null;
        try {
            Generation gen = new Generation();
            Message systemMsg = Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content(systemPrompt)
                    .build();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(userPrompt)
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(Arrays.asList(systemMsg, userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            GenerationResult result = gen.call(param);
            content = result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            log.error("获取错误：{}", e.getMessage());
            log.error("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        return content;
    }

    public static String getSummary(String apiKey, String articleContent) {
        String resultJson = getResult(PromptConstants.SUMMERY_PROMPT, articleContent, apiKey, "qwen-plus");
        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        return jsonObject.getStr("summary", "");
    }
}
